package com.kin207.netty.msg.parse;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kin207.netty.msg.IMessageParse;
import com.kin207.netty.session.Session;

public class SplitMessageParse implements IMessageParse {
	final static Logger logger = LoggerFactory.getLogger(SplitMessageParse.class);
	
	private static SplitMessageParse instance;
	
	private String separator = ",";
	
	private FieldMessageParamUtil fieldMessageParamUtil = new FieldMessageParamUtil();
	public static synchronized SplitMessageParse newInstance(){
		if(instance==null){
			instance = new SplitMessageParse();
		}
		return instance;
	}

	public <T> T parse(String message, Class<T> clazz) {
		String cname = null;
		logger.debug("parse message, message:{}, class:{}", message, clazz);
		if(clazz==null || clazz == Object.class){
			return null;
		}
		String[] msgs = message.split(separator);
		//解析message
		if(msgs.length>0 && MessageConversion.getDeviceId(msgs[1].trim())!=null) {
			cname = MessageConversion.getDeviceId(msgs[1]);
			List<String> list=new ArrayList(Arrays.asList(msgs));
			String msg = list.get(1);
			String cid = list.get(0);
			list.add(0,cname);
			list.add(1,msg);
			list.add(2,cid);
			msgs =  list.toArray(msgs);
		}
		
		T obj = null;
		try {
			obj = clazz.newInstance();
			
			 BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
			 List<FieldMessageParamIndex> fields = fieldMessageParamUtil.getMessageParamFields(clazz);
			 for(FieldMessageParamIndex param : fields){
				 if(param.getIndex()<msgs.length){
					 Object val = msgs[param.getIndex()];
					 logger.debug("parse message, set field:{}, value:{}", param.getField().getName(), val);
					 param.getField().set(obj, val);
				 }
			 }
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
		return obj;
	}
	
	public String getSeparator() {
		return separator;
	}

	public void setSeparator(String separator) {
		this.separator = separator;
	}

	public FieldMessageParamUtil getFieldMessageParamUtil() {
		return fieldMessageParamUtil;
	}

	public void setFieldMessageParamUtil(FieldMessageParamUtil fieldMessageParamUtil) {
		this.fieldMessageParamUtil = fieldMessageParamUtil;
	}
	
}
